package com.yndsoft.jc.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.yndsoft.jc.R;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 更新service
 */
public class UpdateService extends Service {
    private static String down_url;
    private NotificationManager notificationManager;
    private Notification notification;
    private Notification.Builder builder;
    private RemoteViews contentView;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        down_url = intent.getStringExtra("AppUpdateUrl");
        createNotification();
        down(down_url);
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 自动安装的方法，用户点击安装时执行
     */
    private void installApk(File file) {
        Uri uri = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        UpdateService.this.startActivity(intent);
    }

    /**
     * 创建一个通知栏
     */
    public void createNotification() {
        builder = new Notification.Builder(this);
        //设置通知小ICON
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setContentText("正在下载");
        //向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合
        //builder.setDefaults(Notification.DEFAULT_SOUND);
        notification = builder.getNotification();
        //发起正在运行事件（活动中）
        notification.flags = Notification.FLAG_ONGOING_EVENT;
        //点击后消失
        //notification.flags = Notification.FLAG_AUTO_CANCEL;
        //自定义通知栏,先设定RemoteViews
        contentView = new RemoteViews(getPackageName(), R.layout.notification_item);
        //设置对应IMAGEVIEW的ID的资源图片
        contentView.setImageViewResource(R.id.notificationImage, R.drawable.ic_launcher);
        contentView.setTextViewText(R.id.notificationTitle, "电影江湖正在下载");
        contentView.setTextViewText(R.id.notificationPercent, "0%");
        contentView.setProgressBar(R.id.notificationProgress, 100, 0, false);
        notification.contentView = contentView;
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(R.layout.notification_item, notification);
    }

    public void down(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException arg1) {
                Toast.makeText(UpdateService.this, "下载失败", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                int preProgress = 0;
                String DM_TARGET_FOLDER = File.separator + "MovieJH" + File.separator; //下载目标文件夹
                String destFileDir;     //目标文件存储的文件夹路径
                String destFileName;    //目标文件存储的文件名
                destFileDir = Environment.getExternalStorageDirectory() + DM_TARGET_FOLDER;
                destFileName = "电影江湖.apk";
                File dir = new File(destFileDir);
                if (!dir.exists()) dir.mkdirs();
                final File file = new File(dir, destFileName);
                if (file.exists()) file.delete();

                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        //防止界面卡死
                        if (preProgress < progress) {
                            contentView.setTextViewText(R.id.notificationPercent, progress + "%");
                            contentView.setProgressBar(R.id.notificationProgress, 100, progress, false);
                            notificationManager.notify(R.layout.notification_item, notification);
                        }
                        preProgress = progress;
                    }
                    fos.flush();

                    //下载成功
                    //此方法强制弹出安装界面
                    //Uri uri = Uri.fromFile(file);
                    //Intent intent = new Intent(Intent.ACTION_VIEW);
                    //加这个属性是因为使用Context的startActivity方法的话，就需要开启一个新的task
                    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    //intent.setDataAndType(uri, "application/vnd.android.package-archive");
                    //startActivity(intent);
                    //stopSelf();

                    //此方法只有点击通知栏才会弹出安装界面
                    Uri uri = Uri.fromFile(file);
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setDataAndType(uri, "application/vnd.android.package-archive");
                    PendingIntent pendingIntent = PendingIntent.getActivity(UpdateService.this, 0, intent, 0);
                    builder.setContentTitle("电影江湖");
                    builder.setContentText("下载成功");
                    builder.setContentIntent(pendingIntent);
                    Notification notification2 = builder.getNotification();
                    notification2.flags = Notification.FLAG_AUTO_CANCEL;
                    notificationManager.notify(R.layout.notification_item, notification2);
                    stopSelf();
                } catch (final Exception ex) {
                    Toast.makeText(UpdateService.this, "下载失败:" + ex.getMessage(), Toast.LENGTH_LONG).show();
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException ex) {
                        Toast.makeText(UpdateService.this, "下载失败:" + ex.getMessage(), Toast.LENGTH_LONG).show();
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException ex) {
                        Toast.makeText(UpdateService.this, "下载失败:" + ex.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }
}
